package 行为型模式.观察者模式;

import java.util.ArrayList;
import java.util.List;

/**
 * 核心概念
 * Subject (主题): 被观察的对象，维护一个观察者列表，提供添加和删除观察者的方法
 * Observer (观察者): 定义了一个更新接口，用于在主题状态改变时接收通知
 * ConcreteSubject (具体主题): 实现主题接口，存储具体状态，状态改变时通知观察者
 * ConcreteObserver (具体观察者): 实现观察者接口，维护一个对具体主题的引用
 */

//订阅
class Subscribe
{
	List<Release> releaseList = new ArrayList<>();
	private String mes;

	public String getMes() {
		return mes;
	}

	public void setMes(String mes) {
		System.out.println("更新"+mes);
		this.mes = mes;
	}
	
	public void add(Release release)
	{
		releaseList.add(release);	
	}
	
	public void del(Release release)
	{
		releaseList.stream().forEach(r -> {
			if(r.equals(release))
				releaseList.remove(r);
		});
	}
}

//发布(观察者)
class Release
{
	private Subscribe subscribe;

	Release(Subscribe subscribe) {
		this.subscribe = subscribe;
		subscribe.add(this);
	}

	public void update(String mes)
	{
		System.out.print(this.hashCode()+":");
		subscribe.setMes(mes);
	}
}

public class Observer 
{
	public static void main(String[] args) 
	{
		Subscribe subscribe = new Subscribe();

		Release A = new Release(subscribe);
		Release B = new Release(subscribe);
		
		A.update("on.1");
		B.update("on.2");
	}
}
